package com.yotta.operationdatascreencode.common.exception;

import com.yotta.operationdatascreencode.common.core.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理 在controller层添加通知
 * 如果使用@ControllerAdvice，则方法上需要添加@ResponseBody
 */
@RestControllerAdvice
public class UnifiedExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(UnifiedExceptionHandler.class);

    /**
     * 未定义异常 当controller中抛出Exception，则捕获
     */
    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.failed("服务器内部错误");
    }

    /**
     * 自定义业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    public R handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return R.error(null,e.getMessage());
    }

    /**
     * 参数异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        return R.error(null,e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

}
